import frappe
from frappe import _
from frappe.model.document import Document

class UserPreference(Document):
    """
    用户偏好设置
    用于存储用户对界面元素的个性化设置
    """
    
    def before_insert(self):
        """插入前验证"""
        if not self.user:
            self.user = frappe.session.user
    
    def validate(self):
        """验证文档"""
        self.validate_user()
        self.validate_preference_keys()
    
    def validate_user(self):
        """验证用户"""
        if not self.user:
            frappe.throw(_("用户不能为空"))
        
        # 确保用户只能修改自己的偏好设置（除非是管理员）
        if self.user != frappe.session.user and "System Manager" not in frappe.get_roles():
            frappe.throw(_("您只能修改自己的偏好设置"))
    
    def validate_preference_keys(self):
        """验证偏好设置键值"""
        valid_keys = [
            "hide_right_sidebar",
            "sidebar_position",
            "theme_mode",
            "compact_mode",
            "show_animations"
        ]
        
        if self.preference_key not in valid_keys:
            frappe.throw(_("无效的偏好设置键: {0}").format(self.preference_key))
    
    @staticmethod
    def get_user_preference(user, preference_key):
        """
        获取用户特定偏好设置
        
        Args:
            user (str): 用户名
            preference_key (str): 偏好设置键
            
        Returns:
            bool: 偏好设置值
        """
        if not user:
            return False
            
        preference = frappe.get_value(
            "User Preference",
            {
                "user": user,
                "preference_key": preference_key
            },
            "preference_value"
        )
        
        return bool(preference == "1" or preference is True)
    
    @staticmethod
    def set_user_preference(user, preference_key, value):
        """
        设置用户特定偏好设置
        
        Args:
            user (str): 用户名
            preference_key (str): 偏好设置键
            value (bool): 偏好设置值
        """
        if not user:
            return
            
        preference_value = "1" if value else "0"
        
        # 查找现有记录
        existing_preference = frappe.get_value(
            "User Preference",
            {
                "user": user,
                "preference_key": preference_key
            },
            "name"
        )
        
        if existing_preference:
            # 更新现有记录
            frappe.db.set_value(
                "User Preference",
                existing_preference,
                "preference_value",
                preference_value
            )
        else:
            # 创建新记录
            doc = frappe.get_doc({
                "doctype": "User Preference",
                "user": user,
                "preference_key": preference_key,
                "preference_value": preference_value
            })
            doc.insert()
        
        frappe.db.commit()

@frappe.whitelist()
def get_all_user_preferences(user=None):
    """
    获取用户所有偏好设置
    
    Args:
        user (str, optional): 用户名，默认为当前用户
        
    Returns:
        dict: 偏好设置字典
    """
    if not user:
        user = frappe.session.user
    
    preferences = frappe.get_all(
        "User Preference",
        filters={"user": user},
        fields=["preference_key", "preference_value"],
        as_list=True
    )
    
    result = {}
    for key, value in preferences:
        result[key] = bool(value == "1" or value is True)
    
    return {
        "success": True,
        "preferences": result,
        "user": user
    }

@frappe.whitelist()
def set_preference(preference_key, value, user=None):
    """
    设置用户偏好设置
    
    Args:
        preference_key (str): 偏好设置键
        value (bool): 偏好设置值
        user (str, optional): 用户名，默认为当前用户
        
    Returns:
        dict: 操作结果
    """
    try:
        if not user:
            user = frappe.session.user
        
        UserPreference.set_user_preference(user, preference_key, bool(value))
        
        return {
            "success": True,
            "message": f"偏好设置 '{preference_key}' 已更新",
            "preference_key": preference_key,
            "value": bool(value)
        }
    except Exception as e:
        frappe.log_error(f"设置用户偏好设置失败: {str(e)}")
        return {
            "success": False,
            "error": str(e)
        }